module.exports = function(app){

	var User = require('../models/user');

	// --------------------------authentication routes ---------------------
	// Define a middleware function to be used for every secured routes 
	var auth = function(req, res, next){ 
		if (!req.isAuthenticated()) res.send(401); 
		else next(); 
	}; 

	// route to test if the user is logged in or not for angularjs ,use session,is fast
	app.get('/api/loggedin', function(req, res) { 
		// res.send(req.isAuthenticated() ? req.user : '0');
		// console.log('/api/loggedin:req.user:');//---------------------------
		// console.log(req.user); 
		if(req.isAuthenticated()){
			res.send({
		    	_id: req.user.user._id,
       			email: req.user.user.email,
       			username: req.user.user.username,
			});
		}else{res.send('0')}
	});

	//in order to get authinfo realtime and see update changes,instead of request info inside req.session(will not change until login again)
	// only request this route when user refresh their page. this route is not as fast as '/api/loggedin'
	app.get('/api/authinfo',function(req,res){
		if (req.isAuthenticated()){
			User.findOne({_id:req.user.user._id},{_id:1,email:1,username:1},
			function(err,user){
				if (err) { return console.log(err);res.send('0'); };
				res.send(user);
			});
		}else{
			res.send('0');
		}
	});

	// route to log in 
	// app.post('/api/login', app.passport.authenticate('local'), function(req, res) { 
	// 	res.send(req.user); 
	// }); 
	app.post('/api/login', function(req, res,next) { 
		app.passport.authenticate('local', function(err, user, info) {
		    if (err) { return res.send(err); }
		    if (!user) { //incorrect 
		    	// return res.redirect('/login'); 
		    	return res.send(info);
		    }
		    req.logIn(user, function(err) {
		      if (err) { return res.send(err); }
		      console.log('login:return:');//--------------------------------------
		      console.log(user);
		      return res.send(user);
		    });
  		})(req,res,next)
	}); 

	// route to log out 
	app.get('/api/logout', function(req, res){ 
		req.logOut(); 
		res.send('success'); 
	}); 
	// ---------------------------------------

	app.get('/api/protected',auth,function(req,res){
		res.send('this is some protected content!');
	})
	app.get('/api/none',function(req,res){
		res.send(404);
	})

}